package com.cn.march.base.weChatUtil;

import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.cn.march.base.protocol.WeChatTextMsg;
import com.thoughtworks.xstream.XStream;

public class CheckUtil {

	private static final String token = "march";

	public static final String MESSAGE_TEXT = "text";
	public static final String MESSAGE_IMAGE = "image";
	public static final String MESSAGE_VOICE = "voice";
	public static final String MESSAGE_VIDEO = "video";
	public static final String MESSAGE_LOCATION = "location";
	public static final String MESSAGE_LINK = "link";
	public static final String MESSAGE_EVENT = "event";
	public static final String MESSAGE_SUBSCRIBE = "subscribe";
	public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
	public static final String MESSAGE_CLICK = "CLICk";
	public static final String MESSAGE_VIEW = "VIEW";

	/** 校验微信加密签名，接入微信 */
	public static boolean checkSignature(String signature, String timestamp, String nonce) {
		String[] arr = new String[] { token, timestamp, nonce };
		// 排序
		Arrays.sort(arr);

		StringBuffer sb = new StringBuffer();
		for (String str : arr) {
			sb.append(str);
		}
		// 加密后的信息
		String temp = getSha1(sb.toString());

		return temp.equals(signature);// 与微信传过来的加密签名比较
	}

	public static String getSha1(String str) {
		if (null == str || 0 == str.length()) {
			return null;
		}
		char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
		try {
			MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
			mdTemp.update(str.getBytes("UTF-8"));

			byte[] md = mdTemp.digest();
			int j = md.length;
			char[] buf = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
				buf[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(buf);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 当普通微信用户向公众账号发消息时，微信服务器将POST消息的XML数据包发送到服务器，需要把xml文件转化为map。
	 * 
	 * @throws Exception
	 */
	public static Map<String, String> xmltoMapMessage(HttpServletRequest req) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		InputStream in = req.getInputStream();
		// 获取dom树
		Document doc = reader.read(in);
		Element root = doc.getRootElement();
		List<Element> eles = root.elements();
		for (Element e : eles) {
			map.put(e.getName(), e.getText());
		}
		in.close();
		return map;

	}

	/** 当服务器对微信请求参数处理后，需要以xml的形式返回给微信，map->xml */
	public static String textMsgToXml(WeChatTextMsg msg) {
		XStream xStream = new XStream();
		xStream.alias("xml", msg.getClass());
		return xStream.toXML(msg);
	}

	/** 定义一个主菜单 */
	public static String menuText() {
		StringBuffer menu = new StringBuffer();
		menu.append("欢迎你的关注，请根据你的喜好选择进行操作：\n\n");
		menu.append("1、程序猿私藏干货\n");
		menu.append("2、高清无码鼓励师\n");
		menu.append("3、农民播种区域\n");
		menu.append("回复？回到此菜单\n");
		return menu.toString();
	}

	public static String initText(String fromUserName, String toUserName, String content) {
		WeChatTextMsg msg = new WeChatTextMsg();
		msg.setToUserName(fromUserName);
		msg.setFromUserName(toUserName);
		msg.setMsgType(CheckUtil.MESSAGE_TEXT);
		msg.setCreateTime(new Date().getTime());
		msg.setContent(CheckUtil.menuText());
		return CheckUtil.textMsgToXml(msg);
	}
	
	/**1、程序猿私藏干货*/
	public static String backOne(String fromUserName, String toUserName, String content){
		WeChatTextMsg msg = new WeChatTextMsg();
		msg.setToUserName(fromUserName);
		msg.setFromUserName(toUserName);
		msg.setMsgType(CheckUtil.MESSAGE_TEXT);
		msg.setCreateTime(new Date().getTime());
		msg.setContent("银城派-佳玉帮到你！！");
		return CheckUtil.textMsgToXml(msg);
	}
	
	/**2、高清无码鼓励师*/
	public static String backTwo(String fromUserName, String toUserName, String content){
		WeChatTextMsg msg = new WeChatTextMsg();
		msg.setToUserName(fromUserName);
		msg.setFromUserName(toUserName);
		msg.setMsgType(CheckUtil.MESSAGE_TEXT);
		msg.setCreateTime(new Date().getTime());
		msg.setContent("银城派-嘉荣：你是傻逼吗？");
		return CheckUtil.textMsgToXml(msg);
	}
	
	/**3、农民播种区域*/
	public static String backThree(String fromUserName, String toUserName, String content){
		WeChatTextMsg msg = new WeChatTextMsg();
		msg.setToUserName(fromUserName);
		msg.setFromUserName(toUserName);
		msg.setMsgType(CheckUtil.MESSAGE_TEXT);
		msg.setCreateTime(new Date().getTime());
		msg.setContent("86版西游记海外版720P（password 1024）");
		return CheckUtil.textMsgToXml(msg);
	}

}
